package practice;

/**
 * 第一天练习
 */
public class Day1 {

    /**
     * 1.原地删除数组中元素(只留一个)
     * 输入：nums = [0,0,1,1,1,2,2,3,3,4]
     * 输出：5, nums = [0,1,2,3,4]
     */
    public int removeDuplicates1(int[] nums) {
        int i = 0;
        int j = 0;
        for(i = 0; i < nums.length; i++) {
            if(nums[i] != nums[j]) {
                j++;
                nums[j] = nums[i];
            }
        }
        return j + 1;
    }
    /**
     * 2.原地删除数组中元素(留两个)
     * 输入：nums = [0,0,1,1,1,1,2,3,3]
     * 输出：7, nums = [0,0,1,1,2,3,3]
     */
    public int removeDuplicates2(int[] nums) {
        int n = nums.length;
        if(n <= 2) {
            return n;
        }
        int left = 2;
        int right = 2;
        while(right < n) {
            if(nums[left - 2] != nums[right]) {
                nums[left++] = nums[right];
            }
            right++;
        }
        return left;
    }


    /**
     * 3.轮转数组
     * 输入: nums = [1,2,3,4,5,6,7], k = 3
     * 输出: [5,6,7,1,2,3,4]
     */
    private void reverse(int[] nums,int begin,int end) {
        while(begin < end) {
            int tmp = nums[begin];
            nums[begin] = nums[end];
            nums[end] = tmp;
            begin++;
            end--;
        }
    }
    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        reverse(nums,0,nums.length - 1);
        reverse(nums,0,k - 1);
        reverse(nums,k,nums.length - 1);
    }

    /**
     * 4.验证回文串
     * 输入: s = "A man, a plan, a canal: Panama"
     * 输出：true
     * 解释："amanaplanacanalpanama" 是回文串。
     */

    private boolean isAlfAndNumber(char c) {
        if(!Character.isLetter(c) && !Character.isDigit(c)) {
            return false;
        }
        return true;
    }
    public boolean isPalindrome(String s) {
        String str = s.toLowerCase();
        int left = 0;
        int right = s.length() - 1;
        while(left < right) {
            while(left < right && !isAlfAndNumber(str.charAt(left))) {
                left++;
            }
            while(left < right && !isAlfAndNumber(str.charAt(right))) {
                right--;
            }
            if(str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}
